package com.neo.tiny.codegen.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.neo.tiny.codegen.entity.GenDatasourceConf;
import com.neo.tiny.codegen.mapper.GenDatasourceConfMapper;
import com.neo.tiny.codegen.service.GenDatasourceConfService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jasypt.encryption.StringEncryptor;
import org.springframework.stereotype.Service;

import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * @author yqz
 * @Description
 * @CreateDate 2022/8/4 14:09
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class GenDatasourceConfServiceImpl extends ServiceImpl<GenDatasourceConfMapper, GenDatasourceConf>
        implements GenDatasourceConfService{

    private final StringEncryptor stringEncryptor;


    /**
     * 保存数据源并且加密
     * @param conf
     * @return
     */
    @Override
    public Boolean saveDsByEnc(GenDatasourceConf conf) {
        // 校验配置合法性
        if (!checkDataSource(conf)) {
            return Boolean.FALSE;
        }

        // 更新数据库配置
        conf.setPassword(stringEncryptor.encrypt(conf.getPassword()));
        this.baseMapper.insert(conf);
        return Boolean.TRUE;
    }

    /**
     * 更新数据源
     * @param conf 数据源信息
     * @return
     */
    @Override
    public Boolean updateDsByEnc(GenDatasourceConf conf) {
        if (!checkDataSource(conf)) {
            return Boolean.FALSE;
        }


        // 更新数据库配置
        if (StrUtil.isNotBlank(conf.getPassword())) {
            conf.setPassword(stringEncryptor.encrypt(conf.getPassword()));
        }
        this.baseMapper.updateById(conf);
        return Boolean.TRUE;
    }


    /**
     * 通过数据源名称删除
     * @param dsId 数据源ID
     * @return
     */
    @Override
    public Boolean removeByDsId(Long dsId) {

        this.baseMapper.deleteById(dsId);
        return Boolean.TRUE;
    }

    /**
     * 校验数据源配置是否有效
     * @param conf 数据源信息
     * @return 有效/无效
     */
    @Override
    public Boolean checkDataSource(GenDatasourceConf conf) {
        try {
            DriverManager.getConnection(conf.getUrl(), conf.getUsername(), conf.getPassword());
        }
        catch (SQLException e) {
            log.error("数据源配置 {} , 获取链接失败", conf.getName(), e);
            return Boolean.FALSE;
        }
        return Boolean.TRUE;
    }

}
